package com.primaryedu.ui.app.parentsch;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.QuestiondetailsBean;
import com.primaryedu.bean.SelfBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷调查
 *
 * @author jun.wang
 * @description
 * @data 2018年1月8日
 */
public class QuestionActivity extends BaseActivity implements OnClickListener, QuestionAdapter.Callback {
    private ListView listView;
    QuestionAdapter adapter;
    private List<QuestiondetailsBean.DataBean.QuestionDetailListBean> questionLists = new ArrayList<>();
    private List<QuestiondetailsBean.DataBean.QuestionDetailListBean> questiontempList = new ArrayList<>();
    private QuestionAdapter questionAdapter;
    private List<SelfBean> selfLists = new ArrayList<>();
    private List<String> userBeans = new ArrayList<>();
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1001:
                    if (null != questiontempList && questiontempList.size() != 0) {
                        questionAdapter = new QuestionAdapter(QuestionActivity.this, questiontempList, QuestionActivity.this);
                        listView.setAdapter(questionAdapter);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private String questionId;
    private Integer opinion = null;
    private int opinions;
    private JSONObject json;
    private JSONArray jsonArray;
    private JSONObject jsons;
    private boolean isState;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_question);

        init();
        requestQuestionList();
    }

    private void init() {
        Intent intent = getIntent();
        //id
        questionId = intent.getStringExtra("id");
        String name = intent.getStringExtra("name");
        Log.i("yy", "init: voteId=====" + questionId);
        ((TextView) findViewById(R.id.title)).setText(name);
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.bt_question_submit).setOnClickListener(this);

        listView = (ListView) this.findViewById(R.id.listView);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				showToast("第" + position +"被点击");
            }
        });
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_question;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bt_question_submit:
//				submit();
                //判断是否答完题
                isState = true;
                //判断是否答完题
                if (opinion != null) {
                    for (int i = 0; i < questiontempList.size(); i++) {
                        //判断是否有题没答完
                        if (questiontempList.get(i).getQue_state() == 0) {
                            Toast.makeText(getApplicationContext(), "您第" + (i + 1) + "题没有答完", Toast.LENGTH_LONG).show();
                            isState = false;
                            break;
                        } else {

                        }
                    }
                    if (isState) {
                        checkSubmitted();//验证用户是否提交过问卷调查
                    }
                }
                break;
            default:
                break;
        }
    }

    private void checkSubmitted() {//验证用户是否提交过问卷调查
        showLoading("提交中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.questiondetailSubmitted,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=questiondetailSubmit=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("submitted");
                                if (listStr.equals("1")) {
                                    showToast("您已提交过，无法重复提交！");
                                } else if (isState) {
                                    submit();//提交
                                }
                                System.out.println("leaveLists==" + listStr);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("userId", GlobalData.getUserId(QuestionActivity.this));
                map.put("surveyId", questiontempList.get(opinion).getSurveyId());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void submit() {
        showLoading("加载中...");
        json = new JSONObject();
        try {
            json.put("userId", GlobalData.getUserId(this));
            json.put("userName", GlobalData.getUsername(this));
            json.put("surveyId", questiontempList.get(opinion).getSurveyId());
            json.put("questionId", questiontempList.get(opinion).getOptionList().get(opinions).getQuestionId());
            json.put("optionId", questiontempList.get(opinion).getOptionList().get(opinions).getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("yy", "submit:==== " + GlobalData.getUserId(this));
        Log.i("yy", "submit:==== " + GlobalData.getUsername(this));
        Log.i("yy", "submit:surveyId==== " + questiontempList.get(opinion).getSurveyId());
        Log.i("yy", "submit:questionId==== " + questiontempList.get(opinion).getOptionList().get(opinions).getQuestionId());
        Log.i("yy", "submit:optionId==== " + questiontempList.get(opinion).getOptionList().get(opinions).getId());
        Log.i("yy", "submit:==== " + json.toString());

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.questiondetailSubmit,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=questiondetailSubmit=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            String reason = json.getString("reason");
                            if (result == 1) {
                                showToast("提交成功");
                                finish();
//								System.out.println("leaveLists=="+listStr);
                            }else {
                                showToast(reason);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("answers", userBeans.toString());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestQuestionList() {
        showLoading("加载中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.questiondetailspageList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=questionpageList=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("questionDetailList");

                                questionLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<QuestiondetailsBean.DataBean.QuestionDetailListBean>>() {
                                        }.getType());
                                questiontempList.clear();
                                questiontempList.addAll(questionLists);

                                handler.sendEmptyMessage(1001);
                                System.out.println("leaveLists==" + listStr);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", questionId);
                map.put("userId", GlobalData.getUserId(QuestionActivity.this));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void click(View v) {
//		showToast("您点击的是选项：" + qt.getOptionList().get((Integer)v.getTag()).getOption());
        opinion = (Integer) v.getTag();
        //用户选择的是哪个选项（0，1，2，3）
        opinions = questiontempList.get((Integer) v.getTag()).getOpinions();
        Log.i("yy", "click: opinion====" + opinion);
        Log.i("yy", "click: opinionsid====" + questiontempList.get(opinion).getOptionList().get(opinions).getId());
        json = new JSONObject();
        try {
            json.put("userId", GlobalData.getUserId(this));
            json.put("userName", GlobalData.getUsername(this));
            json.put("surveyId", questiontempList.get(opinion).getSurveyId());
            json.put("questionId", questiontempList.get(opinion).getOptionList().get(opinions).getQuestionId());
            json.put("optionId", questiontempList.get(opinion).getOptionList().get(opinions).getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        userBeans.add(String.valueOf(json));
        selfLists = new Gson().fromJson(userBeans.toString(),
                new TypeToken<List<SelfBean>>() {
                }.getType());
        for (int i = 0; i < selfLists.size() - 1; i++) {
            for (int j = 0; j < selfLists.size(); j++) {
                if (i != j) {
                    if (selfLists.get(i).getQuestionId() == selfLists.get(j).getQuestionId()) {
                        userBeans.remove(i);
                    }
                }
            }
        }
        Log.i("yy", "click: userBeans====" + userBeans.toString());
    }
}
